/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package View;

import IO.ApplicationResourcesCheck;
import IO.FileFormat.Project;
import IO.ImageHelper;
import IO.InvalidFolderException;
import IO.ResourceCharacterLocation;
import IO.ResourceNotFoundException;
import IO.XML.LoadConfiguration;
import Model.Action;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import static java.lang.Thread.sleep;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 *
 * @author Walter
 */
public class MainMenu extends javax.swing.JFrame {
    private ImageIcon triste;
    private int actionNumber = 0;
    private Object selectedItem;
    private boolean fullScreen = false;
    private Container previousContentPane;
    private int previousPanelWidth = 0;
    private int previousPanelHeight = 0;
    JPanel panel;
    private boolean playAnimationLoop = false;
    
    Map<Integer, DraggableImageComponent> ListOfDragables =  new HashMap<Integer, DraggableImageComponent>();//
    
    public MainMenu() {
        triste = new ImageIcon(getClass().getResource("/images/nino_triste.png")); 
        try {  
            Configuration.Configuration.MasterFolder = "Carpeta Maestra";
            LoadConfiguration confLoad = new LoadConfiguration();
            if(checkRequiedAssets()){
                initComponents();
                this.getContentPane().setBackground(Color.white);
                setButtonImages();
                Color color = new Color(Integer.parseInt(Configuration.Configuration.BackgroundRGB.get("Red")), Integer.parseInt(Configuration.Configuration.BackgroundRGB.get("Green")), Integer.parseInt(Configuration.Configuration.BackgroundRGB.get("Blue")));
                jPanel2.setBackground(color);
                jPanel2.setLayout(null);
                CustomCellRenderer renderer = new CustomCellRenderer();
                this.ListActions.setCellRenderer(renderer);
                setDeleteButton();
                initializePlayMenu();
            }else{
                System.exit(0);
            }
        } catch (Exception ex) {
            Logger.getLogger(MainMenu.class.getName()).log(Level.WARNING, null, ex);
            JOptionPane.showMessageDialog(this,
            "No se encuentran los recursos mínimos requeridos para funcionar: "+ex.getMessage(),
            "C (Crítico)",
            JOptionPane.INFORMATION_MESSAGE,triste);
            System.exit(0);
        } 
    }
    
    public void initializePlayMenu(){
            panel = new JPanel();
            panel.setSize(300, 100);
            
            JButton buttonPlay = new JButton("Ejecutar");
            buttonPlay.setSize(100, 90);
            setImageToButton(buttonPlay,"/View/assets/play.png",60);
            panel.add(buttonPlay);
            buttonPlay.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mousePressed(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mouseExited(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }
        });
            
            JButton buttonPause = new JButton("Pausar");
            buttonPause.setSize(100, 90);
            setImageToButton(buttonPause,"/View/assets/pausa.png",60);
            panel.add(buttonPause);
            buttonPause.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mousePressed(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mouseExited(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }
        });
            
            JButton buttonStop = new JButton("Detener");
            buttonStop.setSize(100, 90);
            setImageToButton(buttonStop,"/View/assets/Volver a Editor.png",60);
            panel.add(buttonStop);
            buttonStop.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if(fullScreen){
                    unGoFullScreen();
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void mouseExited(MouseEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }
        });
            
            panel.setVisible(true);
    }
    
    public void loadProject(Project project){
    }
    
    private void goFullScreen() {
        Window w = SwingUtilities.windowForComponent(jPanel2);
        previousPanelWidth = jPanel2.getWidth();
        previousPanelHeight = jPanel2.getHeight();
        if (w instanceof JFrame) {
            JFrame frame = (JFrame) w;
            frame.dispose();
            frame.setUndecorated(true);
            frame.getGraphicsConfiguration().getDevice().setFullScreenWindow(w);
            previousContentPane = frame.getContentPane();
            frame.setContentPane(jPanel2);
            frame.add(panel);
            frame.revalidate();
            frame.repaint();
            frame.setVisible(true);
            fullScreen = true;
        }
    }
    
    private void unGoFullScreen() {
        Window w = SwingUtilities.windowForComponent(jPanel2);
        jPanel2.setSize(previousPanelWidth, previousPanelHeight);
        if (w instanceof JFrame) {
            JFrame frame = (JFrame) w;
            frame.dispose();
            frame.setUndecorated(false);
            frame.getGraphicsConfiguration().getDevice().setFullScreenWindow(null);
            frame.setContentPane(previousContentPane);
            jPanel3.add(jPanel2);
            frame.revalidate();
            jPanel2.remove(panel);
            frame.repaint();
            frame.setVisible(true);
            fullScreen = false;
        }
   }
    
    private boolean checkRequiedAssets() {
        ApplicationResourcesCheck checker = new ApplicationResourcesCheck();
        try {
            checker.MasterFolderExists();
            checker.CheckEscenariosFolder();
            checker.CheckPersonajesFolder();
            checker.CheckAudiosFolder();
            checker.CheckEscenariosImages();
            checker.CheckPersonajesFolders();
            checker.CheckAudioFiles();
            checker.CheckPersonajesFoldersContent();
            return true;
        } catch (ResourceNotFoundException ex) {
            Logger.getLogger(MainMenu.class.getName()).log(Level.WARNING, null, ex);
            JOptionPane.showMessageDialog(this,
            "No se encuentran los recursos mínimos requeridos para funcionar: "+ex.getDetail(),
            "C (Crítico)",
            JOptionPane.INFORMATION_MESSAGE,triste);
            return false;
        } catch (InvalidFolderException ex) {
            Logger.getLogger(MainMenu.class.getName()).log(Level.WARNING, null, ex);
            JOptionPane.showMessageDialog(this,
            "No se encuentran los recursos mínimos requeridos para funcionar: "+ex.getDetail(),
            "C (Crítico)",
            JOptionPane.INFORMATION_MESSAGE,triste);
            return false;
        }
    }
    
    
    public void setActionOnImage(int key, Action newAction){
        DraggableImageComponent dragImg = this.ListOfDragables.get(key);
        
    }
    
    private void setImageToButton(JButton button, String imagePath, int size){
        ImageIcon imgIcn = (new javax.swing.ImageIcon(getClass().getResource(imagePath)));
        button.setIcon(new ImageIcon(imgIcn.getImage().getScaledInstance(size, size, Image.SCALE_SMOOTH)));
        button.setOpaque(false);
        button.setContentAreaFilled(false);
        button.setBorderPainted(false);
        button.setVerticalTextPosition(SwingConstants.BOTTOM);
        button.setHorizontalTextPosition(SwingConstants.CENTER);
    }

    private void setButtonImages(){
        setImageToButton(btnNew, "/View/assets/nuevo.png",100);
        setImageToButton(btnOpen, "/View/assets/abrir_proyecto.png",100);
        setImageToButton(btnSave, "/View/assets/guardar.png",100);
        setImageToButton(btnAgregarEscenario, "/View/assets/agregar-cambiar escenario.png",100);
        setImageToButton(btnAgregarPersonaje, "/View/assets/agregar personaje.png",100);
        setImageToButton(btnPlay, "/View/assets/play.png",100);
        setImageToButton(btnExit, "/View/assets/salir_aplicacion.png",100);
    }
    
    private void setDeleteButton(){
        ImageIcon imgIcn = (new javax.swing.ImageIcon(getClass().getResource("/View/assets/equis2.png")));
        btnDeleteAction.setIcon(new ImageIcon(imgIcn.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH)));
        btnDeleteAction.setOpaque(false);
        btnDeleteAction.setContentAreaFilled(false);
        btnDeleteAction.setBorderPainted(false);
        btnDeleteAction.setVerticalTextPosition(SwingConstants.BOTTOM);
        btnDeleteAction.setHorizontalTextPosition(SwingConstants.CENTER);
    }
    
    public void addImage(String imagePath){
        Image img = (new javax.swing.ImageIcon((imagePath))).getImage();
        //ImageIcon originalIcon = new ImageIcon("~/Pictures/apple.png");
        DraggableImageComponent photo;
        if(!ListOfDragables.isEmpty())
        {
            int last= ListOfDragables.size();
            photo = new DraggableImageComponent(last,this);
             ListOfDragables.put(last,photo);
        }
        else
        {
            photo = new DraggableImageComponent(0,this);
            ListOfDragables.put(0,photo);
        }
        
        jPanel2.add(photo);//Adds this component to main container
        photo.setImage(img);//Sets image
        photo.setOpaque(false);
        photo.setAutoSize(true);//The component get ratio w/h of source image
        photo.setOverbearing(true);//On click ,this panel gains lowest z-buffer        
        int delta = jPanel2.getWidth() / 4;
        int cx = jPanel2.getWidth() / 2;
        int cy = jPanel2.getHeight() / 2;
        photo.setSize(250, 250);
        photo.setLocation(Integer.parseInt(Configuration.Configuration.InitialXY.get("x")),Integer.parseInt(Configuration.Configuration.InitialXY.get("y")));
        
        jPanel2.repaint();
    }
  
    
    
    public void addImage(String imagePath, String characterType){
        Image img = (new javax.swing.ImageIcon((imagePath))).getImage();
        //ImageIcon originalIcon = new ImageIcon("~/Pictures/apple.png");
        DraggableImageComponent photo;
        if(!ListOfDragables.isEmpty())
        {
            int last= ListOfDragables.size();
            photo = new DraggableImageComponent(last,this, characterType);
             ListOfDragables.put(last,photo);
        }
        else
        {
            photo = new DraggableImageComponent(0,this,characterType);
            ListOfDragables.put(0,photo);
        }
        
        jPanel2.add(photo);//Adds this component to main container
        photo.setImage(img);//Sets image
        photo.setOpaque(false);
        photo.setAutoSize(true);//The component get ratio w/h of source image
        photo.setOverbearing(true);//On click ,this panel gains lowest z-buffer        
        int delta = jPanel2.getWidth() / 4;
        int cx = jPanel2.getWidth() / 2;
        int cy = jPanel2.getHeight() / 2;
        photo.setSize(250, 250);
        photo.setLocation(Integer.parseInt(Configuration.Configuration.InitialXY.get("x")),Integer.parseInt(Configuration.Configuration.InitialXY.get("y")));
        
        jPanel2.repaint();
    }
    
    public JPanel getMainPanel(){
        return this.jPanel2;
    }
    
    public static int getRandom(int range) {
        int r = (int) (Math.random() * range) - range;
        return r;
    }
    
    public void updateDraggableObject(int id,DraggableComponent modified){
        DraggableImageComponent newDraggable = this.ListOfDragables.get(id);
        
        newDraggable.DraggableComponentX= modified.DraggableComponentX;
        newDraggable.DraggableComponentY= modified.DraggableComponentY;
        //this.ListOfDragables.replace(id, newDraggable);
    }
    
    public int findactionParent(int idaction){
        Map<Integer, DraggableImageComponent>  list =getOrderedListOfActions();
        int idReturn=-1;
        Iterator printOrderedlist = list.entrySet().iterator();
        while (printOrderedlist.hasNext()) {
            Entry thisEntry = (Entry) printOrderedlist.next();
            DraggableImageComponent Dic = (DraggableImageComponent) thisEntry.getValue();
            int accionID = (int)thisEntry.getKey();
            if(idaction== accionID){
                idReturn= Dic.id;
            }
        }
        return idReturn;
   
    }
    
    public DraggableImageComponent findDraggableParent(int idaction){
        Map<Integer, DraggableImageComponent>  list =getOrderedListOfActions();
        DraggableImageComponent returndag = null;
        Iterator printOrderedlist = list.entrySet().iterator();
        while (printOrderedlist.hasNext()) {
            Entry thisEntry = (Entry) printOrderedlist.next();
            DraggableImageComponent Dic = (DraggableImageComponent) thisEntry.getValue();
            int accionID = (int)thisEntry.getKey();
            if(idaction== accionID){
                returndag= Dic;
            }
        }
        return returndag;
   
    }
    
    /*
    /*IMEC of Draggable Actions
     */
     public void addActionDraggableObject(int idDrag, int velocity, String type, String sound){
        
        DraggableImageComponent dic = this.ListOfDragables.get(idDrag);
        String selectedCharacterType = dic.selectedCharacterType;
        this.ListOfDragables.get(idDrag).addAction(actionNumber, velocity, type, sound, selectedCharacterType);
        actionNumber++;
        this.ListActions.setListData(this.getAccions().toArray());

    }
     
       public void addActionDraggableObject(int idDrag, int velocity, String type, String sound,String selectedCharacterType){
        
        DraggableImageComponent dic = this.ListOfDragables.get(idDrag);
        //String selectedCharacterType = dic.selectedCharacterType;
        this.ListOfDragables.get(idDrag).addAction(actionNumber, velocity, type, sound, selectedCharacterType);
        actionNumber++;
        this.ListActions.setListData(this.getAccions().toArray());

    }
    
    public void updateActionDraggableObject(int idDrag,int idaction, int velocity, String type, String sound){
        this.ListOfDragables.get(idDrag).updateAction(idaction, velocity, type,sound);
    }
     
    public void deleteEntry(int idDrag, int toDeleteid){
        if(this.ListOfDragables.get(idDrag) != null){
            this.ListOfDragables.get(idDrag).deleteAccion(toDeleteid);
        }
    }
    
    public void updateActions(){
        this.ListActions.setListData(this.getAccions().toArray());
    }
     
     /* int actionID, Draggable owner*/
     public Map<Integer, DraggableImageComponent> getOrderedListOfActions(){
         
        Map<Integer, DraggableImageComponent> orderedActionList =  new TreeMap<Integer, DraggableImageComponent>();
        
        //Iterate through all the components getting and ordering the accions the actions
        Iterator entries = this.ListOfDragables.entrySet().iterator();
        while (entries.hasNext()) {
          Entry thisEntry = (Entry) entries.next();
          DraggableImageComponent current = (DraggableImageComponent) thisEntry.getValue();
           for (Action ac: current.listOfactions) {
              orderedActionList.put( ac.getID(),current );
            }
        }
        
        Iterator printOrderedlist = orderedActionList.entrySet().iterator();
        while (printOrderedlist.hasNext()) {
             Entry thisEntry = (Entry) printOrderedlist.next();
             DraggableImageComponent Dic = (DraggableImageComponent) thisEntry.getValue();
             System.out.println("esta mierda funciona e imprime: Action#"+ thisEntry.getKey() + "valueObj#"+ Dic.id);
        }
        return orderedActionList;
     }
    
     
     public ArrayList<Action> getAccions(){
        Map<Integer, DraggableImageComponent>  list =getOrderedListOfActions();
        ArrayList<Action> actions = new  ArrayList<Action>();
         
        Iterator printOrderedlist = list.entrySet().iterator();
        while (printOrderedlist.hasNext()) {
            Entry thisEntry = (Entry) printOrderedlist.next();
            DraggableImageComponent Dic = (DraggableImageComponent) thisEntry.getValue();
            int accionID = (int)thisEntry.getKey();
            for (Action ac: Dic.listOfactions) {
                if(ac.getID()==accionID){
                    actions.add(ac);
                }
            }
        }
        return actions;
     }
     
     
     /*
     animateAction: Recive and Action and create the frames to animated
     */
     public void animateAction(Action current){
        Graphics g = jPanel2.getGraphics();
  
        DraggableImageComponent dragimage= findDraggableParent(current.getID());
        int velocityX= 0;
        int velocityY= 0;
        ImageHelper imgHelper= new ImageHelper();
        
        //Set the velocity Directions
        switch (current.getMovementType()) {
            case "Adelante":
                velocityX= current.getdX();
                velocityY= 0;
                break;
            case "Atras":
                velocityX= current.getdX()*-1;
                velocityY= 0;
                break;
            case "Saltar":
                velocityX= 0;
                velocityY= current.getdX()*-1;
                break;
            case "Voltear":
                dragimage.rotate=!dragimage.rotate;
            break;
        }

        ResourceCharacterLocation res = new ResourceCharacterLocation();
        ArrayList<Image> imgArray = res.loadImgArrayList(dragimage.selectedCharacterType,current.getMovementType());
        current.images = imgArray;
        for (int i = 0; i < current.images.size(); i++) {

            Image img = imgHelper.getMirroredImage(current.getSequence(), dragimage.rotate);
            dragimage.DraggableComponentX= dragimage.DraggableComponentX +velocityX;
            dragimage.DraggableComponentY= dragimage.DraggableComponentY +velocityY;
            dragimage.setImage(img);//Sets image
            dragimage.setOpaque(false);
            dragimage.setAutoSize(true);//The component get ratio w/h of source image
            dragimage.setOverbearing(true);//On click ,this panel gains lowest z-buffer        
            dragimage.setSize(250, 250);
            dragimage.setLocation(dragimage.DraggableComponentX,dragimage.DraggableComponentY);

             try { 
                 Thread.sleep(60);
                jPanel2.paintImmediately(0,0,getWidth(),getHeight());
             }
             catch (InterruptedException e) { }
             }
                
        }
     
     
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnNew = new javax.swing.JButton();
        btnOpen = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnPlay = new javax.swing.JButton();
        btnAgregarEscenario = new javax.swing.JButton();
        btnAgregarPersonaje = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        ListActions = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        btnDeleteAction = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(java.awt.Color.white);
        setExtendedState(MAXIMIZED_BOTH);

        jPanel1.setBackground(java.awt.Color.white);

        btnNew.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        btnNew.setText("Nuevo Proyecto");
        btnNew.setToolTipText("Nuevo Proyecto");
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });

        btnOpen.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        btnOpen.setText("Abrir Proyecto");
        btnOpen.setToolTipText("Abrir Proyecto");
        btnOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenActionPerformed(evt);
            }
        });

        btnSave.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        btnSave.setText("Guardar Proyecto");
        btnSave.setToolTipText("Guardar Proyecto");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnPlay.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        btnPlay.setText("Ejecutar");
        btnPlay.setToolTipText("Ejecutar");
        btnPlay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPlayActionPerformed(evt);
            }
        });

        btnAgregarEscenario.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        btnAgregarEscenario.setText("Agregar/Editar Escenario");
        btnAgregarEscenario.setToolTipText("Agregar/Editar Escenario");
        btnAgregarEscenario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarEscenarioActionPerformed(evt);
            }
        });

        btnAgregarPersonaje.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        btnAgregarPersonaje.setText("Agregar Personaje");
        btnAgregarPersonaje.setToolTipText("Agregar Personaje");
        btnAgregarPersonaje.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarPersonajeActionPerformed(evt);
            }
        });

        btnExit.setFont(new java.awt.Font("Trebuchet MS", 0, 14)); // NOI18N
        btnExit.setText("Salir");
        btnExit.setToolTipText("Salir");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnNew, javax.swing.GroupLayout.PREFERRED_SIZE, 120, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btnOpen, javax.swing.GroupLayout.PREFERRED_SIZE, 120, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 120, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btnPlay, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btnAgregarEscenario, javax.swing.GroupLayout.PREFERRED_SIZE, 120, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btnAgregarPersonaje, javax.swing.GroupLayout.PREFERRED_SIZE, 120, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btnExit, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnNew, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnOpen, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnSave, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnPlay, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnAgregarEscenario, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnAgregarPersonaje, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        ListActions.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ListActionsMouseClicked(evt);
            }
        });
        ListActions.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                ListActionsValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(ListActions);

        jLabel1.setFont(new java.awt.Font("Trebuchet MS", 0, 24)); // NOI18N
        jLabel1.setText("Acciones:");

        btnDeleteAction.setText("Eliminar");
        btnDeleteAction.setToolTipText("Eliminar Accion");
        btnDeleteAction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionActionPerformed(evt);
            }
        });

        jPanel2.setBackground(java.awt.Color.white);
        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
        jPanel2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPanel2MouseClicked(evt);
            }
        });
        jPanel2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPanel2KeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnDeleteAction)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(btnDeleteAction))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE))
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnOpenActionPerformed

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        this.deleteEntry(0,2);
        Map<Integer, DraggableImageComponent> algo= this.getOrderedListOfActions();
    }//GEN-LAST:event_btnNewActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        goFullScreen();
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlayActionPerformed
        // TODO add your handling code here:
        
        goFullScreen();
        if(!this.ListOfDragables.isEmpty()){
            ArrayList<Action> orderedActions = this.getAccions();
            playAnimationLoop=true;
            
            for (int i = 0; i < orderedActions.size(); i++) {
                this.animateAction(orderedActions.get(i)); // animate actions in order
                //sleep beetween animations
                try {
                    sleep(30);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_btnPlayActionPerformed

    private void btnAgregarEscenarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarEscenarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnAgregarEscenarioActionPerformed

    private void btnAgregarPersonajeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarPersonajeActionPerformed
        AddCharacterForm addCharacter = new AddCharacterForm(this);
        addCharacter.setVisible(true);
    }//GEN-LAST:event_btnAgregarPersonajeActionPerformed

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_btnExitActionPerformed

    private void ListActionsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_ListActionsValueChanged
        // TODO add your handling code here:
        selectedItem = this.ListActions.getSelectedValue();
        
    }//GEN-LAST:event_ListActionsValueChanged

    private void btnDeleteActionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionActionPerformed
        // TODO add your handling code here:
        if(selectedItem==null)
            return;
        
        Action selectedAction = (Action)selectedItem;
        int dragID = findactionParent(selectedAction.getID());
        deleteEntry(dragID, selectedAction.getID());
        this.ListActions.setListData(this.getAccions().toArray());
        //deleteEntry(selectedAction., WIDTH);
    }//GEN-LAST:event_btnDeleteActionActionPerformed

    private void ListActionsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ListActionsMouseClicked
        // TODO add your handling code here:
        if(evt.getClickCount()>=2){
            this.selectedItem = ListActions.getSelectedValue();
            Action action = (Action)this.selectedItem;
            int velocity = action.getdX();
            int id = action.getID();
            String actionValue = action.getMovementType();
            String sound = action.getSoundPath();
            CharacterActionForm charActionForm = new CharacterActionForm(findDraggableParent(id), this, id, velocity, sound, actionValue);
            charActionForm.setVisible(true);
        }
    }//GEN-LAST:event_ListActionsMouseClicked

    private void jPanel2KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPanel2KeyPressed

    }//GEN-LAST:event_jPanel2KeyPressed

    private void jPanel2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel2MouseClicked

    }//GEN-LAST:event_jPanel2MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainMenu().setVisible(true);
            }
        });
    }
    
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList ListActions;
    private javax.swing.JButton btnAgregarEscenario;
    private javax.swing.JButton btnAgregarPersonaje;
    private javax.swing.JButton btnDeleteAction;
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnOpen;
    private javax.swing.JButton btnPlay;
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
